package cn.dc406.labc406mgr.controller;

import cn.dc406.labc406mgr.entity.ApplyTable;
import cn.dc406.labc406mgr.entity.User;
import cn.dc406.labc406mgr.mapper.ApplyMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
public class ApplyController {
    @Autowired
    ApplyMapper applyMapper;
    @RequestMapping("/getApplyList")
    List<ApplyTable> getApplyList(HttpSession httpSession)
    {
        User user=(User) httpSession.getAttribute("user");
        String username= user.getUsername();
        System.out.println("usernmae="+username);
        List<ApplyTable> list=applyMapper.selectApplyTableByUser(username);
        System.out.println(list);
        return list;
    }

    @CrossOrigin
    @RequestMapping("/refreshApplyNum")
    int refreshApplyNum(@RequestBody ApplyTable applyTable)
    {
        System.out.println(applyTable.getNum()+"+"+applyTable.getId());
        int res=applyMapper.updateLenddetailsById(applyTable.getNum(),applyTable.getId());
        return res;
    }

    @CrossOrigin
    @PostMapping("/applyItemsById")
    int applyItemsById(@RequestBody List<ApplyTable> applyTables)
    {
        System.out.println("applyTables:"+applyTables);
        int res=0;
        for(int i=0;i<applyTables.size();i++)
        {
            res+=applyMapper.applyItemById(new Date(),
                    applyTables.get(i).getId());
        }
        return res==applyTables.size()?1:0;
    }

    @CrossOrigin
    @PostMapping("/deleteAppliesByIds")
    int deleteAppliesByIds(@RequestBody JSONObject jsonObject)
    {
        JSONArray ids=jsonObject.getJSONArray("id");
        System.out.println("ids="+jsonObject);
        int res=0;
        for (int i=0;i<ids.size();i++) {
            int id=ids.getInt(i);
            res += applyMapper.deleteLenddetailsById(id);
        }

        if(res==ids.size())//影响条数达标
        {
            return 1;
        }else{
            return 0;
        }
    }

}
